package com.taoye.thread;

public class Demo24 {
	public static void main(String[] args) throws InterruptedException {
		Demo24Service service = new Demo24Service();
		Thread t = new Demo24Thread(service);
		t.setName("A");
		t.start();
		Thread t2 = new Demo24Thread(service);
		t2.setName("B");
		t2.start();
	}
}

class Demo24Service {
	synchronized public void fun() {
		if(Thread.currentThread().getName().equals("A")) {
			for (int i = 0; i < 100; i++) {
				System.out.println("线程A来访问fun了,i的值:"+i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(i == 2) {
					System.out.println("线程A抛出异常了");
					throw new RuntimeException();
				}
			}
		}else {
			System.out.println(Thread.currentThread().getName()+"线程来执行fun方法了");
		}
	}
}

class Demo24Thread extends Thread {
	private Demo24Service service;
	
	public Demo24Thread(Demo24Service service) {
		this.service = service;
	}
	@Override
	public void run() {
		service.fun();
	}
}
